package Action;

import Action.Sys.Setting;
import Bean.Log.SystemLogEntity;
import Bean.Log.UserLogEntity;
import Bean.UserinfoEntity;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;
import org.hibernate.Session;
import tools.HibernateTools;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;

//此类被用户端复用,谨慎在本类对登录状况进行额外验证
public class AltUser extends ActionSupport {
    HttpServletRequest request;
    int modify_id;
    String err="";
    private String username;
    private String check_password;//用户管理员也是通过此字段区分,管理员null即可
    private String password;
    private String name;
    private String phone;
    private Integer age;
    UserinfoEntity userinfoEntity;
    List<UserLogEntity> userLogEntities;//提供管理员日志
    LinkedList<UserLogEntity> User_userLogEntities;//提供给用户的记录--用户资料变更记录--管理员复用

    public String modify() throws Exception{
        Session session=HibernateTools.getSession();
        userinfoEntity=session.get(UserinfoEntity.class, modify_id);
        if (userinfoEntity==null){
            userinfoEntity=new UserinfoEntity();
            userinfoEntity.setId(modify_id);
            userinfoEntity.setUsername("用户已经注销");
        }

//        HibernateTools.commit(session);
        showlog();
        return SUCCESS;
    }

    private void showlog() {
        Session session=HibernateTools.getSession();
        userLogEntities=session.createQuery("from UserLogEntity where userId=? order by timestamp desc ")
                .setParameter(0,userinfoEntity.getId())
                .getResultList();
        User_userLogEntities=new LinkedList<>();
        HashSet<String> filter=new HashSet<>();
        filter.add(Setting.UserLog_flag_UserLogin);
        filter.add(Setting.UserLog_flag_UserLogout);
        filter.add(Setting.UserLog_flag_UserBorrowBook);
        filter.add(Setting.UserLog_flag_UserReturnBook);
        for (UserLogEntity userLogEntity : userLogEntities) {
            //用户端不显示登录记录,借阅记录---只有用户资料变更记录
            if(!filter.contains(userLogEntity.getFlag())){
                User_userLogEntities.addLast(userLogEntity);
            }
        }
        userLogEntities.removeAll(User_userLogEntities);
        LinkedList<UserLogEntity> middle=new LinkedList<>();
        for (UserLogEntity userLogEntity : userLogEntities) {
            middle.addLast(userLogEntity);
            if (middle.size()>40){
                break;
            }
        }
        userLogEntities=new LinkedList<>(middle);

        //筛选以获得日志分类
        HibernateTools.commit(session);
    }

    public String alt() throws Exception {
        clearErrorsAndMessages();
        Session session = HibernateTools.getSession();
        request = ServletActionContext.getRequest();
        //检查管理员权限--委托给拦截器
        if (!checkManage()) {
            err="权限不足,请您先登录";
//            addActionError("权限不足,请您先登录");
//            request.getSession().setAttribute("err", "权限不足,请您先登录");
//            request.getSession().setAttribute("message", "");
            addActionError(err);

            return INPUT;
        }
        userinfoEntity=session.get(UserinfoEntity.class,modify_id);

        //数据合法性检查
        if (!UserDataCheck()){
            addActionError(err);
            showlog();
//            request.getSession().setAttribute("err", err);
//            SendUserData();
//            request.getSession().setAttribute("message", "");
            return INPUT;
        }
        //数据封装
        updateUserinfoEntity();
        //修改数据库

        session.update(userinfoEntity);

//        request.getSession().setAttribute("message", err);
        addActionMessage("用户信息更新成功");
//        request.getSession().setAttribute("err", err);
        request.getSession().setAttribute("code", true);

        if (check_password==null) {
            UserLogEntity.addLog(userinfoEntity, this);//管理员修改信息
            // 系统日志
            SystemLogEntity.addLog((Integer) ActionContext.getContext().getSession().get("adminid"), this, Setting.SystemLog_flag_AltUserData, userinfoEntity.getId(), SystemLogEntity.remark_user);
        }
        else
            UserLogEntity.addLog(userinfoEntity,Setting.UserLog_flag_UserUpdateUserInfo);//用户修改信息
        showlog();
        return SUCCESS;
    }
    //将用户填写的数据回写
    private void SendUserData() {
        HttpSession httpSession = request.getSession();
        httpSession.setAttribute("username",username);
        httpSession.setAttribute("check_password",check_password);
        httpSession.setAttribute("name",name);
        httpSession.setAttribute("age",age);
        httpSession.setAttribute("password",password);
        httpSession.setAttribute("phone",phone);

    }

    private boolean UserDataCheck() {
        //数据完整度检测
        if (username==null||username.equals(""))
            err+="请输入用户名\n";

        if (check_password!=null){//来着用户
            if (check_password.equals("")||password.equals("")){
//                用户不修改密码

            }else {
                if (!check_password.equals(password)){
                    err+="两次密码不一致\n";
                }
                if (password.length()<6)
                    err+="密码位数需要大于等于6\n";
            }

        }else {//来自管理员
            if (password==null||password.equals(""))
                err+="请输入密码\n";
            if (password==null||password.length()<6)
                err+="密码位数需要大于等于6\n";

        }
        if (phone==null||!tools.TelCheckTools.isValidPhoneNumber(phone))
            err+="请输入正确的电话号码";
        if (err.length()>0)
            return false;
        return true;
    }

    private boolean checkManage() {
        //预留接口,管理员校验在拦截器
        return true;
    }

    public void getRequestData() {
        username = request.getParameter("username");
        check_password = request.getParameter("check_password");
        name = request.getParameter("name");
        try {
            age = Integer.valueOf(request.getParameter("age"));
        }
        catch (Exception e){
            System.err.println(age+"不是数字");
            age=0;
        }
        password = request.getParameter("password");
        phone = request.getParameter("phone");
    }

    public UserinfoEntity updateUserinfoEntity() {
        userinfoEntity.setName(name);
        userinfoEntity.setUsername(username);
        userinfoEntity.setAge(Integer.valueOf(age));
        if (!password.equals(""))//通过检查且不为空,就是可以修改
        userinfoEntity.setPassword(password);
        userinfoEntity.setPhone(phone);
        return userinfoEntity;
    }


    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getCheck_password() {
        return check_password;
    }

    public void setCheck_password(String check_password) {
        this.check_password = check_password;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public HttpServletRequest getRequest() {
        return request;
    }

    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }

    public int getModify_id() {
        return modify_id;
    }

    public void setModify_id(int modify_id) {
        this.modify_id = modify_id;
    }

    public String getErr() {
        return err;
    }

    public void setErr(String err) {
        this.err = err;
    }

    public UserinfoEntity getUserinfoEntity() {
        return userinfoEntity;
    }

    public void setUserinfoEntity(UserinfoEntity userinfoEntity) {
        this.userinfoEntity = userinfoEntity;
    }

    public List<UserLogEntity> getUserLogEntities() {
        return userLogEntities;
    }

    public void setUserLogEntities(List<UserLogEntity> userLogEntities) {
        this.userLogEntities = userLogEntities;
    }

    public LinkedList<UserLogEntity> getUser_userLogEntities() {
        return User_userLogEntities;
    }

    public void setUser_userLogEntities(LinkedList<UserLogEntity> user_userLogEntities) {
        User_userLogEntities = user_userLogEntities;
    }
}